<?php
class Reference_GeoController extends Agitum_Controller_Action
{
    public function completeAction ()
    {
    	$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout()->disableLayout();

    	$term = $this->_request->getParam('query', null);
    	$level = $this->_request->getParam('level', null);
    	if ( !$term ) return;
    	
    	$slot = new Agitum_Model_Cache_Slot_Geo_List(array($term, $level));
		$geo = $slot->load();
		if (!$geo) {
			$geo = Agitum_Model_Geo::search($term, $level);
			foreach( $geo as $id => $row ) {
				$slot->addTag(new Agitum_Model_Cache_Tag_Geo(array('geo'=>$id)));
			}
			$slot->addTag(new Agitum_Model_Cache_Tag_Geo_List(array($term, $level)));
			$slot->save($geo);
		}
		
		$data = array();
		$suggest = array();
		foreach ($geo as $i => $row) {
			$data[] = $row['id'];
			$suggest[] = $row['title'];
		}

//    	$this->_response->setHeader('Content-Type', 'application/json');
		echo Zend_Json::encode(array('query' => $term, 'suggestions' => $suggest, 'data' => $data ));
    }
}